
package br.ufu.lsi.social.storage.loader;

import java.io.BufferedReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import br.ufu.lsi.social.storage.model.User;
import br.ufu.lsi.social.storage.service.UserService;
import br.ufu.lsi.social.storage.util.FileUtil;
import br.ufu.lsi.social.storage.util.PropertiesUtil;

import com.google.gson.Gson;

@Service
public class TwitterLoader {

    private static final Log LOG = LogFactory.getLog( TwitterLoader.class );

    private static final String FOLLOWERS_FILE_PATH = PropertiesUtil.getProperty( "FOLLOWERS_FILE_PATH" );

    
    @Autowired
    UserService userService;

    public void loadFollowersFile( long userId ) {

        try {
            
            BufferedReader reader = FileUtil.openInputFile( FOLLOWERS_FILE_PATH + userId );
            String userRaw = null;            
            while ( ( userRaw = reader.readLine() ) != null ) {
                
                User user = convertToUser( userRaw );
                addUser( user );
            }
        } catch( IllegalStateException e ) {
            
            //LOG.error( "Duplicate node", e );
            e.printStackTrace();
            
        } catch ( Exception e ) {
            e.printStackTrace();
            //LOG.error( "Incorrect file path", e );
        }
    }

    private User convertToUser( String userFile ) {
        
        User user = new Gson().fromJson( userFile, User.class );
        return user;
    }

    private void addUser( User user ) {
        userService.addUser( user );
    }

}
